<script lang="ts" setup>
import * as Yup from 'yup'
import NoGetCode from './_com/NoGetCode.vue'

defineOptions({
  name: 'LoginVerify',
})
definePageMeta({
  layout: 'other',
})
const router = useRouter()

const isCountdown = ref(true)
const { start, reset, current } = useCountDown({
  time: 60 * 1000,
  onFinish() {
    isCountdown.value = false
  },
})
const code = ref('')
const password = ref('')

const paramsString = window.location.search
const searchParams = new URLSearchParams(paramsString)
const curT = ref(searchParams.get('t') || '')
const curN = ref(searchParams.get('n') || '')
const curV = ref(searchParams.get('v') || '')
const isPop = ref(false)
const psdColor = ref('#FC3C3C')

const schema = Yup.object().shape({
  code: Yup.string(),
  password: Yup.string(),
})
function onBack() {
  router.back()
}

/** 发送手机验证码 */
const { runAsync: runAsyncSendPhoneSms, loading: phoneCaptchaLoading } = useRequest(
  () => ApiMemberPhoneSms({ phone: curN.value, type: 0 }),
  {
    onSuccess() {
      message.success($t('success_send_code'))
      onReset()
    },
  },
)
/** 发送邮箱验证码 */
const {
  runAsync: runAsyncMemberSendMailCaptcha,
  loading: emailCaptchaLoading,
} = useRequest(() => ApiMemberSendMailCaptcha({ email: curN.value }), {
  onSuccess() {
    message.success($t('success_send_code'))
    onReset()
  },
})
/** 找回密码接口 */
const { runAsync: runResetPassword, loading: resetLoading } = useRequest(() => ApiMemberPasswordUpdateCode({
  captcha: code.value,
  type: curT.value == 'e' ? 1 : 2,
  new_password: password.value,
  phone_email: curN.value,
}), {
  onSuccess() {
    message.success($t('login_pwd') + $t('success_edit'))
    i18nNavigateTo('/login/signin')
  },
})
const isLoading = computed(() => phoneCaptchaLoading.value || emailCaptchaLoading.value || resetLoading.value)
function onReset() {
  reset()
  start()
  isCountdown.value = true
}
function onResend() {
  if (curT.value == 'e') {
    runAsyncMemberSendMailCaptcha()
    return
  }
  runAsyncSendPhoneSms()
}
function validCode() {
  if (!payPasswordReg.test(code.value))
    return curT.value == 'e' ? $t('validate_msg_regexp_code') : $t('validate_msg_regexp_code_phone')
}

function validPsd(psd: string) {
  if (psd.length < 8)
    return $t('pop_up_create_account_password_least_8_characters')
  else if (!upperLowerReg.test(psd))
    return $t('pop_up_create_account_password_uppercase_lowercase_letter')
  else if (!lastOneNumberReg.test(psd))
    return $t('pop_up_create_account_password_least_1_number')
  return ''
}
function changeBorder(a: string) {
  psdColor.value = a
}
function onSubmit(values: any) {
  const codeErr = validCode()
  if (codeErr) {
    message.error(codeErr)
    return
  }
  if (curV.value) {
    appEventBus.emit(EventBusNames.REG_VERIFY_EMAIL_OR_PHONE, code.value)
    return
  }
  const psdErr = validPsd(values.password)
  if (psdErr) {
    message.error(psdErr)
    return
  }
  runResetPassword()
}
onMounted(() => {
  start()
})
</script>

<template>
  <div class="h-full">
    <div class="size-full bg-[#232626]">
      <div class="relative w-full">
        <BaseImage url="/images/webp/header/h5-header.png" alt="" class="w-full aspect-[414/237]" />
        <div class="absolute top-0 w-full flex justify-between items-center px-6 py-3">
          <div>logo</div>
          <BaseButton class="w-8 !h-8 bg-[rgba(255,255,255,.05)] rounded" type="none" @click="onBack">
            <BaseIcon name="uni-close" class="text-xl" />
          </BaseButton>
        </div>
      </div>

      <div class="py-5 px-6 relative w-full">
        <div class="w-full mb-3">
          <div class="text-base font-semibold mb-1.5">
            {{ `${curT == 'p' ? `${$t('phone')}` : `${$t('email')}`}${$t('verify')}` }}
          </div>
          <template v-if="!curV">
            <div class="text-xs text-[#A8AEB0] font-semibold">
              {{ $t('pls_input_verify_code', { detail: '6' }) }}
            </div>
            <div class="text-xs text-white font-semibold">
              {{ curN }}
            </div>
          </template>
          <template v-else>
            <div class="text-[#A8AEB0] text-xs font-extrabold">
              {{ $t('please_input_your_verification_code2', [curN, 5]) }}
            </div>
          </template>
        </div>
        <div class="mb-3">
          <BaseForm :schema="schema" autocomplete="off" @submit="onSubmit">
            <BaseInput
              name="code"
              required
              class="mb-3"
              :placeholder="$t('verify_code')"
              @update:model-value="v => (code = v)"
            >
              <template #right-icon>
                <BaseButton
                  v-if="isCountdown"
                  disabled
                  class="bg-[#3A4142] text-[#B3BEC1] text-sm h-8 p-1.5 py-0 -mr-1 font-bold rounded-lg"
                  type="none"
                  style="box-shadow: 0px -2px 0px 0px #323738 inset"
                >
                  {{ current.seconds }}S {{ $t('send_again') }}
                </BaseButton>
                <BaseButton
                  v-else
                  class="text-sm h-8 p-1.5 -mr-1 font-bold rounded-lg"
                  type="primary"
                  @click="onResend"
                >
                  {{ $t('resend') }}
                </BaseButton>
              </template>
            </BaseInput>
            <BaseInput
              v-if="!curV"
              name="password"
              type="password"
              required
              class="mb-3"
              :style="{ '--bc-input-focus-border-color': psdColor }"
              :placeholder="$t('password')"
              @update:model-value="v => (password = v)"
            />
            <BasePsdColor v-if="password" :password="password" class="mb-3" @border-color="changeBorder" />
            <BaseButton type="primary" :loading="isLoading" html-type="submit" class="w-full text-xs h-10">
              {{ $t('submit') }}
            </BaseButton>
          </BaseForm>
          <BaseButton type="none" class="text-[#24EE89] mt-1 text-xs font-semibold" @click="() => isPop = true">
            {{ $t('no_get_code') }}
          </BaseButton>
          <BaseBob v-model:show="isPop" :header="$t('no_get_code')">
            <NoGetCode />
          </BaseBob>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>
